package com.kin207.netty.udp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.eventbus.EventBus;
import com.kin207.netty.handle.IMessageHandleAdapter;
import com.kin207.netty.listener.IEventBusListener;
import com.kin207.netty.listener.eventbus.CreatedListenerEvent;
import com.kin207.netty.listener.eventbus.DestroyedListenerEvent;
import com.kin207.netty.msg.IMessageParse;
import com.kin207.netty.server.IServer;
import com.kin207.netty.server.ServerAbs;
import com.kin207.netty.session.SessionManager;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

public class UdpServer  extends ServerAbs {
	final static Logger logger = LoggerFactory.getLogger(UdpServer.class);
	
	public UdpServer(int port) {
		super(port);
	}

	public void run() throws InterruptedException {
		if(sessionManager==null){
			sessionManager = new SessionManager();
		}
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(workerGroup);
			b.option(ChannelOption.SO_BROADCAST, true);
			b.channel(NioDatagramChannel.class);
			b.handler(channelInitializer);

			channelFuture = b.bind(port).sync();
			postCreatedEvent(this);
			logger.info("udp server run success.");
			channelFuture.channel().closeFuture().sync();
		} finally {
			workerGroup.shutdownGracefully();
		}
		logger.info("udp server close.");
		postDestroyedEvent(this);
	}
	
	public String getServerType() {
		return "udp";
	}

	public void close() {
		channelFuture.channel().close();
	}
}
